#!/bin/bash

# macOS version of the Android WiFi setup script.
# adb must be in the same directory as this script. The file must be named adb.

SCRIPT_DIR="$(cd "$(dirname "$0")" 2>/dev/null && pwd -P)" || exit 1
CONFIG_FILE="$SCRIPT_DIR/wifi_config.txt"
ADB="$SCRIPT_DIR/adb"

ADB_TARGET=()
WIFI_ACTION=""
WIFI_SSID=""
WIFI_PWD=""
SELECTED_SERIAL=""
EXIT_REQUESTED=0

printf '\033]0;Android WiFi Setup\007'
clear 2>/dev/null || printf '\033[2J\033[H'

tmp_file() {
    mktemp "${TMPDIR:-/tmp}/$1.XXXXXX"
}

pause_any_key() {
    local prompt="${1:-Press any key to continue...}"
    local pause_key=""
    printf "%s" "$prompt"
    IFS= read -r -n 1 -s pause_key
    printf "\n"
}

close_terminal_window() {
    if [ "${TERM_PROGRAM:-}" != "Apple_Terminal" ] ||
        ! command -v osascript >/dev/null 2>&1; then
        return 0
    fi

    osascript -e 'tell application "Terminal" to close front window' \
        >/dev/null 2>&1
}

adb_cmd() {
    "$ADB" "${ADB_TARGET[@]}" "$@"
}

shell_quote() {
    printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
}

print_colored_wifi_result() {
    local result_kind="$1"
    local result_text="$2"
    local message_color=""
    local wifi_color=""

    if [ "$result_kind" = "success" ]; then
        message_color=$'\033[32m'
        wifi_color=$'\033[36m'
    else
        message_color=$'\033[31m'
        wifi_color=$'\033[33m'
    fi

    printf "%s%s\033[0m%s%s\033[0m\n" \
        "$message_color" "$result_text" "$wifi_color" "$WIFI_SSID"
}

return_to_menu() {
    printf "\n"
    pause_any_key "Press any key to return to the main menu..."
}

check_adb() {
    if [ ! -e "$ADB" ]; then
        if [ -e "$SCRIPT_DIR/adb.exe" ]; then
            echo "[ERROR] Windows adb.exe found. It cannot run on macOS."
            echo "       Please place the macOS version of adb in the same directory and name it adb."
        else
            echo "[ERROR] Local adb not found: $SCRIPT_DIR/adb"
            echo "       Please place the macOS version of adb in the same directory as this script."
        fi
        return 10
    fi

    if [ ! -x "$ADB" ]; then
        echo "[ERROR] The adb in the script directory is not executable: $ADB"
        echo "       Make sure it is a macOS executable with execute permission."
        return 10
    fi

    if ! "$ADB" start-server </dev/null >/dev/null 2>&1; then
        echo "[ERROR] Unable to execute the adb in the script directory: $ADB"
        echo "       Please provide the macOS version of adb. The current Windows adb.exe cannot run on macOS."
        return 10
    fi
    return 0
}

select_device() {
    local state_file=""
    local devices_file=""
    local serial=""
    local state=""
    local rest=""
    local ready_count=0
    local unauth_count=0
    local offline_count=0
    local found_serial=""

    printf "\n== Checking Android devices ==\n"
    if [ -n "${ANDROID_SERIAL:-}" ]; then
        state_file="$(tmp_file adb_state)" || {
            echo "[ERROR] Unable to create a temporary file."
            return 11
        }
        if ! adb_cmd get-state </dev/null >"$state_file" 2>&1; then
            rm -f "$state_file"
            echo "[ERROR] The device specified by ANDROID_SERIAL is unavailable: $ANDROID_SERIAL"
            return 11
        fi
        rm -f "$state_file"
        ADB_TARGET=(-s "$ANDROID_SERIAL")
        SELECTED_SERIAL="$ANDROID_SERIAL"
        echo "[SUCCESS] Connected device: $ANDROID_SERIAL"
        return 0
    fi

    devices_file="$(tmp_file adb_devices)" || {
        echo "[ERROR] Unable to create a temporary file."
        return 14
    }
    adb_cmd devices </dev/null >"$devices_file" 2>&1 || true

    while IFS=$' \t' read -r serial state rest; do
        if [ "$state" = "device" ]; then
            ready_count=$((ready_count + 1))
            found_serial="$serial"
        elif [ "$state" = "unauthorized" ]; then
            unauth_count=$((unauth_count + 1))
        elif [ "$state" = "offline" ]; then
            offline_count=$((offline_count + 1))
        fi
    done <"$devices_file"
    rm -f "$devices_file"

    if [ "$ready_count" -eq 0 ]; then
        if [ "$unauth_count" -gt 0 ]; then
            echo "[ERROR] Device unauthorized. Unlock the phone, tap "Allow" in the USB debugging authorization dialog, and run the script again."
            return 12
        fi
        if [ "$offline_count" -gt 0 ]; then
            echo "[ERROR] Device is offline. Reconnect the USB cable, make sure USB debugging is enabled, and run the script again."
            return 13
        fi
        echo "[ERROR] No Android device detected. Connect the phone via USB and enable USB debugging."
        return 14
    fi

    if [ "$ready_count" -gt 1 ]; then
        echo "[ERROR] Multiple Android devices detected. Keep only one connected, or set ANDROID_SERIAL before running the script."
        "$ADB" devices </dev/null
        return 15
    fi

    ADB_TARGET=(-s "$found_serial")
    SELECTED_SERIAL="$found_serial"
    echo "[SUCCESS] Connected device: $SELECTED_SERIAL"
    return 0
}

enable_wifi() {
    local enable_file=""
    local status_file=""

    printf "\n== Enable WiFi ==\n"
    enable_file="$(tmp_file adb_wifi_enable)" || {
        echo "[ERROR] Unable to create a temporary file."
        return 20
    }

    if ! adb_cmd shell svc wifi enable </dev/null >"$enable_file" 2>&1; then
        if ! adb_cmd shell cmd wifi set-wifi-enabled enabled </dev/null >>"$enable_file" 2>&1; then
            echo "[ERROR] Failed to enable WiFi. ADB output:"
            cat "$enable_file"
            rm -f "$enable_file"
            return 20
        fi
    fi
    sleep 3

    status_file="$(tmp_file adb_wifi_status)" || {
        rm -f "$enable_file"
        echo "[ERROR] Unable to create a temporary file."
        return 20
    }
    adb_cmd shell cmd wifi status </dev/null >"$status_file" 2>&1 || true
    if grep -Fqi "Wifi is enabled" "$status_file"; then
        echo "[SUCCESS] WiFi enabled."
    else
        echo "[INFO] The WiFi enable command was sent, but the state could not be confirmed. The script will still try to connect."
        cat "$status_file"
    fi
    rm -f "$enable_file" "$status_file"
    return 0
}

select_wifi_menu() {
    local menu_choice=""

    printf "\n========== WiFi Setup Menu ==========\n"
    echo "1. Connect to a new WiFi network"
    echo "2. Connect to the last saved WiFi network"
    echo "3. Exit"
    echo "=================================="
    WIFI_ACTION=""
    if ! IFS= read -r -p "Choose an option (1/2/3): " menu_choice; then
        echo "[INFO] No menu input received. Exiting."
        return 44
    fi

    case "$menu_choice" in
        1)
            WIFI_ACTION="new"
            return 0
            ;;
        2)
            WIFI_ACTION="saved"
            return 0
            ;;
        3)
            WIFI_ACTION="exit"
            EXIT_REQUESTED=1
            return 0
            ;;
        *)
            echo "[INFO] Invalid option. Please enter 1, 2, or 3."
            select_wifi_menu
            return $?
            ;;
    esac
}

load_saved_wifi() {
    if [ ! -f "$CONFIG_FILE" ]; then
        echo "[INFO] No previously saved WiFi configuration found. Choose 1 to connect to a new WiFi network."
        return 42
    fi

    WIFI_SSID=""
    WIFI_PWD=""
    IFS= read -r WIFI_SSID <"$CONFIG_FILE" || true
    IFS= read -r WIFI_PWD < <(sed -n '2p' "$CONFIG_FILE") || true
    WIFI_SSID="${WIFI_SSID%$'\r'}"
    WIFI_PWD="${WIFI_PWD%$'\r'}"
    case "$WIFI_SSID" in
        $'\xef\xbb\xbf'*) WIFI_SSID="${WIFI_SSID#$'\xef\xbb\xbf'}" ;;
    esac

    if [ -z "$WIFI_SSID" ] || [ -z "$WIFI_PWD" ]; then
        echo "[INFO] The saved WiFi configuration is invalid. Choose 1 to connect to a new WiFi network."
        return 43
    fi

    echo "[SUCCESS] Using the last saved WiFi: $WIFI_SSID"
    return 0
}

input_wifi() {
    WIFI_SSID=""
    WIFI_PWD=""

    if ! IFS= read -r -p "Enter WiFi name (SSID): " WIFI_SSID || [ -z "$WIFI_SSID" ]; then
        echo "[ERROR] WiFi name cannot be empty."
        return 40
    fi

    if ! IFS= read -r -s -p "Enter WiFi password: " WIFI_PWD || [ -z "$WIFI_PWD" ]; then
        printf "\n"
        echo "[ERROR] WiFi password cannot be empty."
        return 41
    fi
    printf "\n"
    return 0
}

save_wifi_config() {
    if ! printf "%s\n%s\n" "$WIFI_SSID" "$WIFI_PWD" >"$CONFIG_FILE"; then
        echo "[INFO] WiFi connected, but failed to save the configuration: $CONFIG_FILE"
        return 0
    fi
    echo "[SUCCESS] WiFi configuration saved to: $CONFIG_FILE"
    return 0
}

clear_device_wifi() {
    local wifi_list_file=""
    local forget_file=""
    local network_id=""
    local rest=""
    local clear_count=0
    local clear_fail=0

    printf "\n== Clear saved WiFi networks on the device ==\n"
    wifi_list_file="$(tmp_file adb_wifi_list)" || {
        echo "[ERROR] Unable to create a temporary file."
        return 21
    }
    if ! adb_cmd shell cmd wifi list-networks </dev/null >"$wifi_list_file" 2>&1; then
        echo "[ERROR] Failed to read the saved WiFi list from the device. Cannot continue WiFi setup. ADB output:"
        cat "$wifi_list_file"
        rm -f "$wifi_list_file"
        return 21
    fi

    if grep -Eqi "Unknown command|not found|Exception" "$wifi_list_file"; then
        echo "[ERROR] This device does not support cmd wifi list-networks, so saved WiFi networks cannot be cleared. ADB output:"
        cat "$wifi_list_file"
        rm -f "$wifi_list_file"
        return 22
    fi

    while IFS=$' \t' read -r network_id rest; do
        case "$network_id" in
            ""|*[!0-9]*) continue ;;
        esac

        clear_count=$((clear_count + 1))
        forget_file="$(tmp_file adb_wifi_forget)" || {
            clear_fail=$((clear_fail + 1))
            echo "[ERROR] Failed to clear networkId=$network_id:"
            echo "       Unable to create a temporary file."
            continue
        }
        if ! adb_cmd shell cmd wifi forget-network "$network_id" </dev/null >"$forget_file" 2>&1; then
            clear_fail=$((clear_fail + 1))
            echo "[ERROR] Failed to clear networkId=$network_id:"
            cat "$forget_file"
        fi
        rm -f "$forget_file"
    done <"$wifi_list_file"
    rm -f "$wifi_list_file"

    if [ "$clear_fail" -gt 0 ]; then
        return 23
    fi

    if [ "$clear_count" -eq 0 ]; then
        echo "[SUCCESS] No saved WiFi networks on the device. Nothing to clear."
        return 0
    fi

    echo "[SUCCESS] Cleared $clear_count saved WiFi network(s) on the device."
    sleep 1
    return 0
}

verify_wifi_connected() {
    local status_file=""
    local dhcp_file=""
    local list_status_file=""
    local ip_status_file=""

    status_file="$(tmp_file adb_wifi_status_verify)" || return 1
    dhcp_file="$(tmp_file adb_wifi_dhcp)" || {
        rm -f "$status_file"
        return 1
    }
    list_status_file="$(tmp_file adb_wifi_list_status)" || {
        rm -f "$status_file" "$dhcp_file"
        return 1
    }
    ip_status_file="$(tmp_file adb_wifi_ip_status)" || {
        rm -f "$status_file" "$dhcp_file" "$list_status_file"
        return 1
    }

    adb_cmd shell cmd wifi status </dev/null >"$status_file" 2>/dev/null || true
    adb_cmd shell "dumpsys netstats | grep -i 'wifi' | grep -i 'dhcp' | grep -i 'completed'" \
        </dev/null >"$dhcp_file" 2>/dev/null || true
    adb_cmd shell cmd wifi list-networks </dev/null >"$list_status_file" 2>/dev/null || true
    adb_cmd shell "ip addr show wlan0 | grep -i 'inet ' | grep -v '127.0.0.1'" \
        </dev/null >"$ip_status_file" 2>/dev/null || true

    if grep -Fqi "Wifi is connected to" "$status_file" &&
        grep -Fqi -- "$WIFI_SSID" "$status_file"; then
        rm -f "$status_file" "$dhcp_file" "$list_status_file" "$ip_status_file"
        return 0
    fi

    if [ -s "$dhcp_file" ]; then
        rm -f "$status_file" "$dhcp_file" "$list_status_file" "$ip_status_file"
        return 0
    fi

    if grep -Fqi -- "$WIFI_SSID" "$list_status_file" &&
        grep -Eqi "connected|已连接|state=connected" "$list_status_file"; then
        rm -f "$status_file" "$dhcp_file" "$list_status_file" "$ip_status_file"
        return 0
    fi

    if [ -s "$ip_status_file" ]; then
        rm -f "$status_file" "$dhcp_file" "$list_status_file" "$ip_status_file"
        return 0
    fi

    rm -f "$status_file" "$dhcp_file" "$list_status_file" "$ip_status_file"
    return 1
}

detect_auth_failure() {
    local auth_file=""

    auth_file="$(tmp_file adb_wifi_auth)" || return 1
    adb_cmd shell dumpsys wifi </dev/null >"$auth_file" 2>/dev/null || true
    adb_cmd shell logcat -d -t 300 </dev/null >>"$auth_file" 2>/dev/null || true
    if grep -Eqi \
        "WRONG_PASSWORD|AUTHENTICATION_FAILURE|AUTH_FAILURE|PASSWORD_MAY_BE_INCORRECT|authentication failure|wrong password|NETWORK_SELECTION_DISABLED_BY_WRONG_PASSWORD" \
        "$auth_file"; then
        rm -f "$auth_file"
        echo "[ERROR] WiFi authentication failed. The password is likely incorrect."
        return 0
    fi
    rm -f "$auth_file"
    return 1
}

print_wifi_ip_mac() {
    local wifi_ip_file=""
    local wifi_mac_file=""
    local wifi_ip=""
    local wifi_mac=""

    wifi_ip_file="$(tmp_file adb_wifi_ip)" || return 0
    wifi_mac_file="$(tmp_file adb_wifi_mac)" || {
        rm -f "$wifi_ip_file"
        return 0
    }

    adb_cmd shell ip addr show wlan0 </dev/null >"$wifi_ip_file" 2>/dev/null || true
    adb_cmd shell cat /sys/class/net/wlan0/address </dev/null >"$wifi_mac_file" 2>/dev/null || true

    wifi_ip="$(grep -i "inet " "$wifi_ip_file" | grep -vi "127.0.0.1" | awk 'NR == 1 {print $2}')"
    wifi_ip="${wifi_ip%%/*}"
    wifi_mac="$(sed -n '1p' "$wifi_mac_file" | tr -d '\r')"

    if [ -n "$wifi_ip" ]; then
        echo "  WiFi IP address:$wifi_ip"
    fi
    if [ -n "$wifi_mac" ]; then
        echo "  WiFi MAC address:$wifi_mac"
    fi

    rm -f "$wifi_ip_file" "$wifi_mac_file"
    return 0
}

connect_wifi() {
    local connect_file=""
    local wait_seconds=0
    local auth_check_mod=0
    local quoted_ssid=""
    local quoted_pwd=""

    printf "\n== Connect to WiFi: %s ==\n" "$WIFI_SSID"
    adb_cmd shell logcat -c </dev/null >/dev/null 2>&1 || true
    adb_cmd shell svc wifi enable </dev/null >/dev/null 2>&1 || true
    sleep 2

    connect_file="$(tmp_file adb_wifi_connect)" || {
        echo "[ERROR] Unable to create a temporary file."
        return 32
    }
    quoted_ssid="$(shell_quote "$WIFI_SSID")"
    quoted_pwd="$(shell_quote "$WIFI_PWD")"
    adb_cmd shell "cmd wifi connect-network $quoted_ssid wpa2 $quoted_pwd --save" \
        </dev/null >"$connect_file" 2>&1 || true

    if grep -Eqi "Unknown command|not found" "$connect_file"; then
        adb_cmd shell am start -a android.settings.WIFI_SETTINGS </dev/null >/dev/null 2>&1 || true
        echo "ADB output:"
        cat "$connect_file"
        rm -f "$connect_file"
        return 30
    fi

    if grep -Eqi "Invalid args|Exception" "$connect_file"; then
        echo "ADB output:"
        cat "$connect_file"
        rm -f "$connect_file"
        return 32
    fi
    rm -f "$connect_file"

    echo "Checking WiFi connection status. You will be notified when connected (waiting up to 30 seconds)..."
    while :; do
        if verify_wifi_connected; then
            print_colored_wifi_result success "[SUCCESS] Successfully connected to WiFi: "
            echo "Current connection information:"
            echo "  Connected SSID: $WIFI_SSID"
            print_wifi_ip_mac
            return 0
        fi

        wait_seconds=$((wait_seconds + 1))
        auth_check_mod=$((wait_seconds % 3))
        if [ "$auth_check_mod" -eq 0 ] && detect_auth_failure; then
            return 31
        fi

        if [ "$wait_seconds" -ge 30 ]; then
            if detect_auth_failure; then
                return 31
            fi
            echo "Current WiFi status:"
            adb_cmd shell cmd wifi status </dev/null 2>/dev/null || true
            return 32
        fi
        sleep 1
    done
}

main() {
    while :; do
        select_wifi_menu || return $?

        if [ "$WIFI_ACTION" = "exit" ]; then
            return 0
        fi

        ADB_TARGET=()
        SELECTED_SERIAL=""
        if ! check_adb; then
            return_to_menu
            continue
        fi

        if ! select_device; then
            return_to_menu
            continue
        fi

        if ! enable_wifi; then
            return_to_menu
            continue
        fi

        if [ "$WIFI_ACTION" = "new" ]; then
            if ! input_wifi; then
                return_to_menu
                continue
            fi
        else
            if ! load_saved_wifi; then
                return_to_menu
                continue
            fi
        fi

        while :; do
            if ! clear_device_wifi; then
                return_to_menu
                break
            fi

            connect_wifi
            case "$?" in
                0)
                    save_wifi_config
                    echo "[SUCCESS] SSID and password saved for next use."
                    return_to_menu
                    break
                    ;;
                30)
                    print_colored_wifi_result fail "[ERROR] ADB does not support automatic connection. Target WiFi: "
                    echo "[ERROR] This Android system does not support writing WiFi settings through ADB. The phone WiFi settings page has been opened; please connect manually once."
                    return_to_menu
                    break
                    ;;
                31)
                    print_colored_wifi_result fail "[ERROR] Incorrect password or authentication failed. WiFi: "
                    echo "[INFO] Please enter the SSID and WiFi password again, then retry."
                    ;;
                *)
                    print_colored_wifi_result fail "[ERROR] WiFi setup failed. Target WiFi: "
                    echo "       Possible causes: SSID not found, weak signal, incorrect password, non-WPA2 network, or device system restrictions."
                    ;;
            esac

            if ! input_wifi; then
                return_to_menu
                break
            fi
        done
    done
}

main
RET=$?
printf "\n"
if [ "$RET" -eq 0 ]; then
    echo "Execution completed."
else
    echo "Execution failed. Error code: $RET"
fi
printf "\n"
if [ "$EXIT_REQUESTED" -eq 1 ]; then
    pause_any_key "Press any key to exit..."
    close_terminal_window
    exit "$RET"
fi
pause_any_key "Press any key to close the window..."
exit "$RET"
